package com.example.textview;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import java.util.Locale;

public class TextToSpeechActivity extends AppCompatActivity {

    Button btn_speech;
    private TextToSpeech tts;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_text_to_speech);

        tts=new TextToSpeech(TextToSpeechActivity.this, new TextToSpeech.OnInitListener() {
            @Override
            public void onInit(int i) {
                if(i==TextToSpeech.SUCCESS)
                {
                    int result=tts.setLanguage(Locale.CHINESE);
                    if(result==TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED)
                    {
                        Toast.makeText(TextToSpeechActivity.this, "R.string.notAvailable", Toast.LENGTH_SHORT).show();
                    }
                    else {
                        tts.setLanguage(Locale.US);

                    }

                }
            }
        });


        btn_speech=findViewById(R.id.btn_speech);
        btn_speech.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                tts.speak("需要转化的文字", TextToSpeech.QUEUE_FLUSH, null);
            }
        });
    }
}